//
//  CZStatusPictureView.swift
//  sinaWeiboswift
//
//  Created by 段文杰 on 16/4/15.
//  Copyright © 2016年 段文杰. All rights reserved.
//

import UIKit
import SDWebImage
/// collectionViewcell的间距
private let HMStatusPictureViewCellMargin: CGFloat = 4

/// cell的最大列数为3列,列数使用整数
private let HMStatusPictureViewMaxColumn = 3

let CZstatusPictureItemWH = (UIScreen.mainScreen().bounds.width - 2 * HMStatusCellMargin - (CGFloat(HMStatusPictureViewMaxColumn) - 1) * HMStatusPictureViewCellMargin) / CGFloat(HMStatusPictureViewMaxColumn)

//let WH = (UIScreen.mainScreen().bounds.width - 2 *HMStatusCellMargin - (CGFloat(HMStatusPictureViewMaxColumn)-1) * HMStatusPictureViewCellMargin) / CGFloat (HMStatusPictureViewMaxColumn)

class CZStatusPictureView: UICollectionView {
    
    /// 配图NSURL数组
    var pictureURLs: [NSURL]?{
        didSet{
            let size = calcViewSize()
            
            // 自己来约束大小,当cell给pictureURLs之后计算出宽高,然后重行修改约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
//            HMPrint("配图大小: \(size)")
           
            
            reloadData()
        
        }
    
    
    }
    
    func calcViewSize()->CGSize {
      //判断有没有图片

        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        
        flowLayout.itemSize = CGSize(width: CZstatusPictureItemWH, height: CZstatusPictureItemWH)
       
    
        let count = pictureURLs?.count  ?? 0
        
        
        
        if count == 0 {
//            HMPrint("没有图片")
            return CGSizeZero
        }
        
        //一张图片
        if count == 1 {
            self.backgroundColor = UIColor.init(red: ( CGFloat(arc4random_uniform(256)) / 255.0), green: ( CGFloat(arc4random_uniform(256)) / 255.0), blue: ( CGFloat(arc4random_uniform(256)) / 255.0), alpha: 1.0)
//            return CGSizeMake(180, 90)
            
            //设置图片本来的大小
            var size = CGSizeMake(HMStatusIconWH, HMStatusIconWH)
            
            let url = pictureURLs?.first
            
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url?.absoluteString){
            
            size = image.size
            size = CGSizeMake(size.width*UIScreen.mainScreen().scale, size.height*UIScreen.mainScreen().scale)
            }
            
            
            //如果图片太小  或者太大 就要修改一下
            
            if size.width < 60 {
                size.width = 60
            }
            if size.width > scrrenW*0.5 {
                size.width = scrrenW*0.5
            }
            
            flowLayout.itemSize = size
            
            return size
            
        }
        
        var column = HMStatusPictureViewMaxColumn
        flowLayout.minimumInteritemSpacing = HMStatusPictureViewCellMargin
        flowLayout.minimumLineSpacing = HMStatusPictureViewCellMargin
        //两张图片
        if count == 2 || count == 4 {
            column = 2
        }
        //不是两张以外的多张图片
        let row = (count + colum-1) / column
        
        let width = CGFloat(column)*CZstatusPictureItemWH + (CGFloat(column)-1)*HMStatusPictureViewCellMargin
        let height = CGFloat(row)*CZstatusPictureItemWH + (CGFloat(row)-1)*HMStatusPictureViewCellMargin
        self.backgroundColor = UIColor.init(red: ( CGFloat(arc4random_uniform(256)) / 255.0), green: ( CGFloat(arc4random_uniform(256)) / 255.0), blue: ( CGFloat(arc4random_uniform(256)) / 255.0), alpha: 1.0)
        return CGSizeMake(width, height)
        
        
        
    }
    
    
    var  flowLayout = UICollectionViewFlowLayout()
    

    
    
    init(){
    super.init(frame: CGRectZero, collectionViewLayout: flowLayout)
    
        dataSource = self
        
//        self.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        self.registerClass(CZStatusPictureCell.self, forCellWithReuseIdentifier: "cell")

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    
    
}

extension CZStatusPictureView : UICollectionViewDataSource{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count  ?? 0
//        return (pictureURLs?.count)!
    }

    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CZStatusPictureCell
        
        cell.backgroundColor = UIColor.init(red: ( CGFloat(arc4random_uniform(256)) / 255.0), green: ( CGFloat(arc4random_uniform(256)) / 255.0), blue: ( CGFloat(arc4random_uniform(256)) / 255.0), alpha: 1.0)
        
        cell.imageURL = self.pictureURLs![indexPath.item]
        return cell
        
    }
}


class CZStatusPictureCell : UICollectionViewCell {

    
    // 每个cell需要一个图片的URL来取下载图片
    /// didSet是存储性数性才有的
    var imageURL: NSURL? {
        didSet {
            bkgImageView.sd_setImageWithURL(imageURL!)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }
    
    private func prepareUI() {
        // 1.添加控件
        contentView.addSubview(bkgImageView)
        
        // 2.添加约束
        bkgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }
    
    // MARK: - 懒加载
    /// 背景图片
    private lazy var bkgImageView: UIImageView = UIImageView()
}